import pm2 from 'pm2';
import Router from 'koa-router';
import Koa from 'koa';
import json from 'koa-json';
import cors from './app/middleware/cors';

const app = new Koa();
const rootRouter = new Router();

app.use(cors({
  credentials: true,
}));
app.use(json());

function toPromiseFunc(fn) {
  return function promiseFunc() {
    return new Promise((resolve, reject) => {
      fn((err, payload) => {
        if (err) return reject(err);
        return resolve(payload);
      });
    });
  };
}

const connect = toPromiseFunc(pm2.connect.bind(pm2));
const list = toPromiseFunc(pm2.list.bind(pm2));
const waitConnect = connect();

rootRouter.get('/metrics', async (ctx) => {
  await waitConnect;
  const metrics = await list();

  ctx.body = metrics.map((m) => {
    const {
      exec_mode,
      instances,
      status,
      pm_uptime,
      axm_monitor,
      restart_time,
      unstable_restarts,
      created_at,
    } = m.pm2_env;

    return {
      name: m.name,
      execMode: exec_mode,
      instances,
      status,
      upTime: pm_uptime,
      monitors: axm_monitor,
      restartTime: restart_time,
      unstableRestarts: unstable_restarts,
      createdAt: created_at,
      monit: m.monit,
      pid: m.pid,
    };
  });
});

app.use(rootRouter.routes());
const port = process.env.PORT || 5090;
app.listen(port, () => {
  console.log(`Monitor Running at port ${port}`);
});
